package com.htbb.controller.personalInsure;

import java.io.BufferedReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.htbb.common.base.Result1;
import com.htbb.common.base.Results;
import com.htbb.common.util.Base64;
import com.htbb.common.util.SecurityUtils;
import com.htbb.model.personalInsure.entity.YFWBean;
import com.htbb.model.personalInsure.entity.YFWBean2;
import com.htbb.order.entity.BsOrderIsu;
import com.htbb.order.entity.TcClaim;
import com.htbb.order.enums.IsuStatus;
import com.htbb.order.interfaces.BsOrderIsuService;
import com.htbb.order.interfaces.TcClaimService;
import com.htbb.service.personalInsure.IhtbbService;


/**
 * @description 迁移ihtbb项目代码
 * @date 2017-03-02
 * @author wangzhicheng
 *
 */
@RestController
@RequestMapping("/api")
public class IhtbbController {

	private static final Long END = 4070880000000l;
	private static final Logger logger = LoggerFactory.getLogger(IhtbbController.class);

	@Autowired
	private IhtbbService ihtbbService;
	
	@Autowired
	private TcClaimService tcClaimService;
	
	@Autowired
	private BsOrderIsuService bsOrderIsuService;
	
	@RequestMapping(value = "callbackClaim", method = { RequestMethod.POST,RequestMethod.GET}, produces = "application/json;charset=UTF-8")
	public String callbackClaim(HttpServletRequest request, HttpServletResponse response/*,
			@RequestParam(value = "orderId", required = true) String orderId,
			@RequestParam(value = "claimTime", required = true) String claimTime,
			@RequestParam(value = "claimStutas", required = true) String claimStutas,
			@RequestParam(value = "claimMsg", required = true) String claimMsg,
			@RequestParam(value = "AisleCode", required = true) String AisleCode,
			@RequestParam(value = "url1", required = false) String url1,
			@RequestParam(value = "url2", required = false) String url2,
			@RequestParam(value = "url3", required = false) String url3*/) {
		logger.info("=============callbackClaim  start============");
		System.out.println(request.getParameterMap());
		Result1 result = new Result1();
		String orderId = request.getParameter("orderId"); 
		if (StringUtils.isBlank(orderId)) {
			return isEmpty(result, "orderId");
		} 
		String claimTime = request.getParameter("claimTime"); 
		if (StringUtils.isBlank(claimTime)) {
			return isEmpty(result, "claimTime");
		} 
		String claimStutas = request.getParameter("claimStutas"); 
		if (StringUtils.isBlank(claimStutas)) {
			return isEmpty(result, "claimStutas");
		} 
		String claimMsg = request.getParameter("claimMsg"); 
		if (StringUtils.isBlank(claimMsg)) {
			return isEmpty(result, "claimMsg");
		} 
		String AisleCode = request.getParameter("AisleCode"); 
		if (StringUtils.isBlank(AisleCode)) {
			return isEmpty(result, "AisleCode");
		} 
		String url1 = null; 
		String url2 = null; 
		String url3 = null; 
		IsuStatus status = null;
		if(claimStutas.trim().equals("0")){
			status = IsuStatus.NO_CLAIM;			
		} else if (claimStutas.trim().equals("1")){
			status = IsuStatus.FINISH_FOR_CLAIM;
			url1 = request.getParameter("url1");
			url2 = request.getParameter("url2");
			url3 = request.getParameter("url3");
		} else {
			logger.error(" Unknow claimStutas. claimStutas:" + claimStutas);
			result.setMsgCode("failed");
			result.setMsg( "Unknow claimStutas.");
			return JSON.toJSONString(result);
		}
		TcClaim tcClaim = tcClaimService.selectByKey(orderId);
		if (tcClaim == null) {
			logger.error("The order is not query to the data-----orderId :" + orderId);
			result.setMsgCode("failed");
			result.setMsg( "The order is not query to the data.");
			return JSON.toJSONString(result);
		}
		String isuAid = tcClaim.getForm3();
		long claimAid = Long.valueOf(tcClaim.getClaimId());
		boolean b = ihtbbService.updateClaimAndAcctIsu(status, isuAid, claimAid, AisleCode, claimMsg, claimTime, url1,url2, url3);
		if (b){
			result.setMsg("success.");
			result.setMsgCode("success");
			return JSON.toJSONString(result);
		}else{
			result.setMsg("failed.");
			result.setMsgCode("failed");
			return JSON.toJSONString(result);
		}
	}

	@RequestMapping(value = "sendOrder", method = { RequestMethod.POST,RequestMethod.GET }, produces = "text/html;charset=utf-8")
	public String sendOrder(HttpServletRequest request, HttpServletResponse response) {
		Results result = new Results();
		String queryString = null;
		try {
			queryString = getRequestBody(request);
		} catch (IOException e1) {
			e1.printStackTrace();
			result.setMsgCode("failed");
			result.setMsg("request parameters error.");
			String setAESStr = setAESStr(JSON.toJSONString(result));
			return setAESStr;
		}
		logger.info("====queryString:" + queryString);
		String aesStr = getAESStr(queryString);// 解密参数
		if (aesStr == null) {
			result.setMsgCode("failed");
			result.setMsg("request parameters error.");
			String setAESStr = setAESStr(JSON.toJSONString(result));
			return setAESStr;
		}
		YFWBean jb = null;
		try {
			jb = JSON.parseObject(aesStr, YFWBean.class);// 将建json对象转换为YFWBean对象
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("将建json对象转换为YFWBean对象  错误 e:" + e.getMessage());
			result.setMsgCode("failed");
			result.setMsg("request parameters error.");
			String setAESStr = setAESStr(JSON.toJSONString(result));
			return setAESStr;
		}
		String isuName = jb.getIsuName(); // 被保险人姓名
		if (StringUtils.isBlank(isuName)) {
			return setAESStr(isEmptys(result, "isuName"));
		}
		String isuSsn = jb.getIsuSsn(); // 身份证号
		if (StringUtils.isBlank(isuSsn)) {
			return setAESStr(isEmptys(result, "isuSsn"));
		}
		String sendNum = jb.getSendNum(); // 派工单单号
		if (StringUtils.isBlank(sendNum)) {
			return setAESStr(isEmptys(result, "sendNum"));
		}
		Long startTime = jb.getStartTime(); // startTime出发时间（毫秒值）
		if (startTime == null) {
			return setAESStr(isEmptys(result, "startTime"));
		}
		String address = jb.getAddress(); // 地址
		if (StringUtils.isBlank(address)) {
			return setAESStr(isEmptys(result, "address"));
		}
		logger.info("*****sendOrder info isuName：" + isuName + " isuSsn:" + isuSsn + " sendNum:" + sendNum
				+ "startTime:" + startTime + " address:" + address);

		BsOrderIsu bsOrderIsu = new BsOrderIsu();
		bsOrderIsu.setSendNum(sendNum);
	    bsOrderIsu = bsOrderIsuService.selectByOther(bsOrderIsu);
		if (bsOrderIsu != null) {
			result.setMsg("the order exist!");
			result.setMsgCode("failed");
			String setAESStr = setAESStr(JSON.toJSONString(result));
			return setAESStr;
		}
		Date startDate = new Date(startTime);
		try {
			long insertBsOrderIsu = ihtbbService.insertBsOrderIsu(isuName, isuSsn, sendNum, startDate, address);
			jb.setOrderId(insertBsOrderIsu);
			result.setMsg(jb);
			result.setMsgCode("success");
			String setAESStr = setAESStr(JSON.toJSONString(result));
			return setAESStr;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("insert bs_order_isu  table error.   e:" + e.getMessage());
		}
		result.setMsgCode("failed");
		result.setMsg("unknow exception.");
		String setAESStr = setAESStr(JSON.toJSONString(result));
		return setAESStr;
	}

	@RequestMapping(value = "endOrder", method = { RequestMethod.POST,RequestMethod.GET }, produces = "text/html;charset=utf-8")
	public String endOrder(HttpServletRequest request, HttpServletResponse response) {
		Results result = new Results();
		String queryString = null;
		try {
			queryString = getRequestBody(request);
		} catch (IOException e1) {
			e1.printStackTrace();
			result.setMsgCode("failed");
			result.setMsg("request parameters error.");
			String setAESStr = setAESStr(JSON.toJSONString(result));
			return setAESStr;
		}
		String aesStr = getAESStr(queryString);// 解密参数
		if (aesStr == null) {
			result.setMsgCode("failed");
			result.setMsg("request parameters error.");
			String setAESStr = setAESStr(JSON.toJSONString(result));
			return setAESStr;
		}
		YFWBean jb = null;
		try {
			jb = JSON.parseObject(aesStr, YFWBean.class);// 将建json对象转换为YFWBean对象
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("将建json对象转换为YFWBean对象  错误 e:" + e.getMessage());
			result.setMsgCode("failed");
			result.setMsg("request parameters error.");
			String setAESStr = setAESStr(JSON.toJSONString(result));
			return setAESStr;
		}
		Long orderId = jb.getOrderId(); // 订单号
		if (orderId == null) {
			return setAESStr(isEmptys(result, "orderId"));
		}
		String isuName = jb.getIsuName(); // 被保险人姓名
		if (StringUtils.isBlank(isuName)) {
			return setAESStr(isEmptys(result, "isuName"));
		}
		String isuSsn = jb.getIsuSsn(); // 身份证号
		if (StringUtils.isBlank(isuSsn)) {
			return setAESStr(isEmptys(result, "isuSsn"));
		}
		String sendNum = jb.getSendNum(); // 派工单单号
		if (StringUtils.isBlank(sendNum)) {
			return setAESStr(isEmptys(result, "sendNum"));
		}
		Long endTime = jb.getEndTime(); // endTime结单时间（毫秒值）
		if (endTime == null) {
			return setAESStr(isEmptys(result, "endTime"));
		}
		String address = jb.getAddress(); // 地址
		if (StringUtils.isBlank(address)) {
			return setAESStr(isEmptys(result, "address"));
		}
		logger.info("*****endOrder info orderId:" + orderId + " isuName：" + isuName + " isuSsn:" + isuSsn + " sendNum:"
				+ sendNum + " endTime:" + endTime + " address:" + address);
		Date endDate = new Date(endTime);
		try {
			BsOrderIsu bsOrderIsu = ihtbbService.getBsOrderIsu(orderId + "", isuSsn, sendNum);
			if (bsOrderIsu == null) {
				logger.error("The order is not query to the data-----orderId:" + orderId + " isuSsn:" + isuSsn
						+ " sendNum:" + sendNum);
				result.setMsgCode("failed");
				result.setMsg("The order is not query to the data! ");
				return JSON.toJSONString(result);
			}
			long end_time = bsOrderIsu.getEndDate().getTime();
			if (end_time != END) {
				result.setMsgCode("failed");
				result.setMsg("The order is sended! ");
				String setAESStr = setAESStr(JSON.toJSONString(result));
				return setAESStr;
			}
			// 计算费用
			int daysBetween = daysBetween(bsOrderIsu.getStartDate(), endDate);
			int isu_amt = daysBetween * 300;
			bsOrderIsu.setEndDate(endDate);
			ihtbbService.updateBsOrderIsu(Long.parseLong(bsOrderIsu.getToiAid()), bsOrderIsu.getEndDate(), isu_amt);
			jb.setStartTime(bsOrderIsu.getStartDate().getTime());
			result.setMsg(jb);
			result.setMsgCode("success");
			logger.info(JSON.toJSONString(result));
			String setAESStr = setAESStr(JSON.toJSONString(result));
			return setAESStr;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("update bs_order_isu  table error.   e:" + e.getMessage());
		}
		result.setMsg("unknow exception.");
		result.setMsgCode("failed");
		String setAESStr = setAESStr(JSON.toJSONString(result));
		return setAESStr;
	}

	@RequestMapping(value = "queryOrder", method = { RequestMethod.POST,RequestMethod.GET }, produces = "text/html;charset=utf-8")
	public String queryOrder(HttpServletRequest request, HttpServletResponse response) {
		Results result = new Results();
		String queryString = null;
		try {
			queryString = getRequestBody(request);
		} catch (IOException e1) {
			e1.printStackTrace();
			result.setMsgCode("failed");
			result.setMsg("request parameters error.");
			String setAESStr = setAESStr(JSON.toJSONString(result));
			return setAESStr;
		}
		String aesStr = getAESStr(queryString);// 解密参数
		if (aesStr == null) {
			result.setMsgCode("failed");
			result.setMsg("request parameters error.");
			String setAESStr = setAESStr(JSON.toJSONString(result));
			return setAESStr;
		}
		YFWBean jb = null;
		try {
			jb = JSON.parseObject(aesStr, YFWBean.class);// 将建json对象转换为YFWBean对象
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("将建json对象转换为YFWBean对象  错误 e:" + e.getMessage());
			result.setMsgCode("failed");
			result.setMsg("request parameters error.");
			String setAESStr = setAESStr(JSON.toJSONString(result));
			return setAESStr;
		}
		String sendNum = jb.getSendNum(); // 派工单单号
		if (StringUtils.isBlank(sendNum)) {
			return setAESStr(isEmptys(result, "sendNum"));
		}
		logger.info("*****queryOrder info sendNum:" + sendNum);
		try {
			BsOrderIsu bsOrderIsu = new BsOrderIsu();
			bsOrderIsu.setSendNum(sendNum);
		    bsOrderIsu = bsOrderIsuService.selectByOther(bsOrderIsu);
			if (bsOrderIsu == null) {
				logger.error("The order is not query to the data-----sendNum:" + sendNum);
				result.setMsgCode("failed");
				result.setMsg("The order is not query to the data! ");
				String setAESStr = setAESStr(JSON.toJSONString(result));
				return setAESStr;
			}

			YFWBean2 y = new YFWBean2();
			y.setOrderId(Long.parseLong(bsOrderIsu.getToiAid()));
			y.setIsuName(bsOrderIsu.getIsuName());
			y.setIsuSsn(bsOrderIsu.getIsuSsn());
			y.setSendNum(bsOrderIsu.getSendNum());
			y.setStartTime(bsOrderIsu.getStartDate().getTime());
			if (bsOrderIsu.getEndDate().getTime() != END) {
				y.setEndTime(bsOrderIsu.getEndDate().getTime());
				y.setType(1);// 结束订单
			} else {
				y.setType(0);// 创建订单
			}
			y.setAddress(bsOrderIsu.getSendAddress());
			result.setMsg(y);
			result.setMsgCode("success");
			logger.info(JSON.toJSONString(result));
			String setAESStr = setAESStr(JSON.toJSONString(result));
			return setAESStr;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("queryOrder error.   e:" + e.getMessage());
		}
		result.setMsg("unknow exception.");
		result.setMsgCode("failed");
		String setAESStr = setAESStr(JSON.toJSONString(result));
		return setAESStr;
	}

	/**
	 * 判断为空，输出结果
	 * @param result
	 * @param req
	 * @return
	 */
	private String isEmpty(Result1 result, String req){
		logger.error( req + " is null . ");
		result.setMsgCode("failed");
		result.setMsg( req + " is null.");
		return JSON.toJSONString(result);
	}
	private String isEmptys(Results result, String req){
		logger.error( req + " is null . ");
		result.setMsgCode("failed");
		result.setMsg( req + " is null.");
		return JSON.toJSONString(result);
	}
	
	/**
	 * 计算两个日期之间相差的天数
	 * 
	 * @param smdate
	 *            较小的时间
	 * @param bdate
	 *            较大的时间
	 * @return 相差天数
	 * @throws ParseException
	 */
	private int daysBetween(Date smdate, Date bdate) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		smdate = sdf.parse(sdf.format(smdate));
		bdate = sdf.parse(sdf.format(bdate));
		Calendar cal = Calendar.getInstance();
		cal.setTime(smdate);
		long time1 = cal.getTimeInMillis();
		cal.setTime(bdate);
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600);
		between_days = between_days / 24 + 1;
		return Integer.parseInt(String.valueOf(between_days));
	}

	/**
	 * AES解密
	 * 
	 * @param params
	 * @return
	 */
	public static String getAESStr(String params) {
		/*** AES解密 解析参数 ****/
		String obj = null;
		params = Base64.decode(params);
		try {
			SecretKeySpec secretKeySpec = SecurityUtils.getSecretKeySpec(SecurityUtils.KEY.getBytes("UTF-8"));
			byte[] parseHexStr2Byte = SecurityUtils.parseHexStr2Byte(params);
			byte[] decrypt = SecurityUtils.decrypt(parseHexStr2Byte, secretKeySpec);
			obj = new String(decrypt);
		} catch (Exception e) {
			logger.error("AES解密 解析参数 失败  e:" + e.getMessage());
		}
		return obj;
	}

	/**
	 * AES加密
	 * 
	 * @param params
	 * @return
	 */
	public static String setAESStr(String params) {
		SecretKeySpec secretKeySpec;
		byte[] decrypt = null;
		String key = null;
		try {
			secretKeySpec = SecurityUtils.getSecretKeySpec(SecurityUtils.KEY.getBytes("UTF-8"));
			decrypt = SecurityUtils.encrypt(params.getBytes("UTF-8"), secretKeySpec);
		} catch (Exception e) {
			logger.error("AES 加密失败");
			return null;
		}
		key = SecurityUtils.parseByte2HexStr(decrypt);
		return Base64.encode(key);
	}

	/**
	 * 获取请求的 body
	 * 
	 * @param req
	 * @return
	 * @throws IOException
	 */
	private String getRequestBody(HttpServletRequest req) throws IOException {
		BufferedReader reader = req.getReader();
		String input = null;
		StringBuffer requestBody = new StringBuffer();
		while ((input = reader.readLine()) != null) {
			requestBody.append(input);
		}
		return requestBody.toString();
	}

	public static void main(String[] args) {
		
		YFWBean jb = new YFWBean();
		jb.setIsuName("abcd");
		jb.setIsuSsn("362402199104111039");
		jb.setSendNum("77775555");
		jb.setStartTime(544564564l);
		jb.setAddress("江西省");
		
		YFWBean jb1 = new YFWBean();
		jb1.setOrderId(14887890135950882l);
		jb1.setIsuName("abcd");
		jb1.setIsuSsn("362402199104111039");
		jb1.setSendNum("77775555");
		jb1.setEndTime(40708800000l);
		jb1.setAddress("江西省井冈山");
		
		YFWBean jb2 = new YFWBean();
		jb2.setSendNum("77775555");
		
		String jbs = JSON.toJSONString(jb2);
		System.out.println(jbs);
		String s= setAESStr(jbs);
		System.out.println(s);
	}
	
}
